package com.xjzd.std.socket.option;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketTimeoutOption {

    public static void main(String[] args) throws IOException {
        // serverTimeout();
        clientTimeout();
    }

    public static void serverTimeout() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8099);
        Socket socket = serverSocket.accept();
        socket.setSoTimeout(5000); // 设置超时时间为5秒
        InputStream inputStream = socket.getInputStream();
        try {
            byte[] buffer = new byte[1024];
            while (true) {
                int len = inputStream.read(buffer);
                System.out.println(new String(buffer, 0 , len));
            }
        } catch (Exception e) {
            System.out.println(e);
            socket.close();
            serverSocket.close();
        }
    }

    public static void clientTimeout() throws IOException {
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress("192.168.188.2", 8099), 3000);
        // SO_TIMEOUT指socket读取超时时间，不是整个数据传输的超时时间。
        socket.setSoTimeout(5000);
        InputStream inputStream = socket.getInputStream();
        try {
            byte[] buffer = new byte[1024];
            while (true) {
                int len = inputStream.read(buffer);
                if (len == -1) {
                    continue;
                }
                System.out.println(new String(buffer, 0 , len));
            }
        } catch (Exception e) {
            System.out.println(e);
            socket.close();
        }
    }
}
